<template>
  <!-- 拖拽上传区域 -->
  <Disabled :disabled="globalUploadStatus !== 'start'">
    <div
      class="hover:border-primary/70 shadow-card group relative rounded-2xl border-2 border-dashed border-gray-300 bg-white p-4 text-center transition-all duration-300"
    >
      <div class="flex flex-col items-center justify-center">
        <div
          class="bg-primary/10 mb-6 rounded-full p-4 transition-transform duration-300 group-hover:scale-110"
        >
          <i class="iconfont icon-yunshangchuan text-primary text-4xl! md:text-5xl!"></i>
        </div>
        <h3 class="mb-3 text-xl font-medium">拖拽文件到此处上传</h3>
        <p class="mb-6 max-w-md text-center text-gray-500">
          支持分片上传，断点续传，文件总大小不得超过{{ formatFileSize(maxTotalSize) }}
        </p>
        <div class="flex items-center justify-center gap-3">
          <MBtn type="primary" @click="triggerFileInput" title="支持多选"
            ><i class="iconfont icon-wenjian"></i>选择文件</MBtn
          >
          <MBtn type="primary" class="select-file-btn" @click="selectFolder" v-if="folder"
            ><i class="iconfont icon-wenjian"></i>选择文件夹</MBtn
          >
        </div>
        <p class="mt-4 text-xs text-gray-400">支持格式：所有文件类型</p>
      </div>
    </div>
  </Disabled>
  <!-- 操作按钮 -->
  
    <div class="flex flex-wrap gap-3">
      <Disabled :disabled="globalUploadStatus !== 'start' || fileList.length === 0">
        <MBtn type="success" @click="allStart">全部开始</MBtn>
      </Disabled>
      <Disabled :disabled="globalUploadStatus !== 'paused'">
        <MBtn type="warning" @click="allPause">全部暂停</MBtn>
      </Disabled>
      <Disabled :disabled="globalUploadStatus !== 'uploading'">
        <MBtn type="success" @click="allResume">恢复执行</MBtn>
      </Disabled>
      <Disabled :disabled="globalUploadStatus !== 'start' || fileList.length === 0">
        <MBtn type="danger" @click="allDel">清空列表</MBtn>
      </Disabled>
        
    </div>

    <!--  multiple开启多文件选择 -->
    <input
      type="file"
      ref="multipleInputRef"
      style="display: none"
      @change="handleFileChange"
      multiple
      :accept="accept"
    />
    <!-- 文件夹选择 webkitdirectory开启文件夹选择 -->
    <input
      type="file"
      ref="folderInputRef"
      style="display: none"
      @change="handleFileChange"
      webkitdirectory
      :accept="accept"
    />
 
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import MBtn from './MBtn.vue'
import Disabled from './Disabled.vue'

defineOptions({
  name: 'ActionBtns',
})

const props = defineProps({
  globalUploadStatus: {
    type: String,
    default: 'start',
  },
  maxTotalSize: {
    type: Number,
    default: 0,
  },
  addFile: {
    type: Function,
    default: () => ({}),
  },
  allStart: {
    type: Function,
    default: () => ({}),
  },
  allPause: {
    type: Function,
    default: () => ({}),
  },
  allResume: {
    type: Function,
    default: () => ({}),
  },
  allDel: {
    type: Function,
    default: () => ({}),
  },
  // 可选择的文件类型，多个类型用英文逗号隔开
  accept: {
    type: String,
    default: '*',
  },
  // 限制文件夹内文件总大小，默认100MB
  folder: {
    default: false,
  },
  fileList: {
    default: () => [],
    type: Array,
  },
  formatFileSize: {
    type: Function,
    default: (size: number) => {},
  },
})
// const folderMaxSize = computed(() => {
//   if (props.folder && typeof props.folder === 'object') {
//     return (props.folder as { folderMaxSize: number }).folderMaxSize
//   } else {
//     return 0
//   }
// })
const fileAccept = computed(() => {
  if (props.accept === '*') return []
  if (props.accept.includes('mp4')) return [props.accept]
  return props.accept.split(',').map((item) => item.trim())
})

const multipleInputRef = ref()
const folderInputRef = ref()
function triggerFileInput() {
  multipleInputRef.value.click()
}

async function selectFolder() {
  try {
    // 记录文件夹文件列表
    const folderList = ref<File[]>([])
    const dirHandle =
      'showDirectoryPicker' in window && (await (window as any).showDirectoryPicker()) // 用户选择文件夹

    let totalSize = 0

    for await (const entry of dirHandle.values()) {
      if (entry.kind === 'file') {
        const file: any = await entry.getFile()

        // 验证文件格式
        // if (!fileAccept.value.includes(file.type)) {
        //   alert(`文件夹中包含其他类型文件！，请上传${props.accept}类型的文件`)
        //   return false
        // }
        totalSize += file.size
        console.log('文件:', file.name)
        folderList.value.push(file)
      } else {
        alert('文件夹中包含子文件夹！')
        return false
      }
    }

    if (totalSize > props.maxTotalSize) {
      alert(`文件夹大小超过限制！`)
      return false
    }
    handleFileChange({
      target: {
        files: folderList.value,
      },
    })
    return true
  } catch (err) {
    console.error('用户取消选择或出错:', err)
  }
}

function handleFileChange(e: any) {
  const files = e.target.files
  props.addFile(files)
}
</script>

<style scoped lang="scss">
.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;

  button {
    padding: 6px 20px;
    border: none;
    border-radius: 50px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    background: linear-gradient(45deg, #434343, #000000);
    color: white;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  }

  button:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.4);
  }

  button:active {
    transform: translateY(1px);
  }

  button.startBtn {
    background: linear-gradient(45deg, #2193b0, #6dd5ed);
  }

  button.pauseBtn {
    background: linear-gradient(45deg, #ff8c00, #ffcc00);
  }

  button.resumeBtn {
    background: linear-gradient(45deg, #00b09b, #96c93d);
  }

  button.resetBtn {
    background: linear-gradient(45deg, #ff416c, #ff4b2b);
  }
}

.stats-container {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;

  .stats-bar {
    display: flex;
    justify-content: space-around;
    padding: 0px;
    border-radius: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;

    .stat-item {
      text-align: center;
      padding: 10px;
    }

    .stat-value {
      font-size: 2rem;
      font-weight: bold;
      color: #ffcc00;
    }
  }
}
</style>
